import mysql.connector
from mysql.connector import errorcode

from uc.gen_code import genCode


def sync_user_data():
    # 源数据库配置 (sysmandb)
    src_db = {
        # 'host': '10.1.213.159',
        # 'user': 'GTXS_user',
        # 'password': 'GTXS_user_JG123',
        'host': '123.56.171.51',
        'user': 'jg_usercenter',
        'password': 'Jg_usercenter_20250312',
        'database': 'sysmandb'
    }

    # 目标数据库配置 (jg_usercenter)
    dest_db = {
        'host': '123.56.171.51',
        'port': 3306,
        'user': 'jg_usercenter',
        'password': 'Jg_usercenter_20250312',
        'database': 'jg_usercenter_new'
    }

    try:
        # 创建数据库连接
        src_conn = mysql.connector.connect(**src_db)
        dest_conn = mysql.connector.connect(**dest_db)

        src_cursor = src_conn.cursor(dictionary=True)
        dest_cursor = dest_conn.cursor()

        # 1. 查询源数据,注意数据范围
        src_cursor.execute("""
            select tenant_id,
                   id,
                   role_name,
                   role_description,
                   deleted_tag,
                   create_date,
                   create_user,
                   change_date,
                   change_user
            from sys_role WHERE date(create_date) > '2025-05-01'
        """)

        # 2. 准备插入语句（根据实际表结构调整字段）
        insert_query = """
            INSERT INTO sys_role (id, role_name, role_code, description, create_user, create_date, change_user, change_date, 
                app_code, role_group, tenant_id, remark, deleted_tag) 
            VALUES (
                %(id)s, %(role_name)s, %(id)s, %(role_description)s, %(create_user)s, %(create_date)s, %(change_user)s, %(change_date)s,
                'main', 'main_operator', %(tenant_id)s, 'sync from ymt', %(deleted_tag)s
            )
        """

        # 3. 执行同步
        batch_size = 1000
        count = 0

        for user in src_cursor:
            processed_user = dict(user)  # 创建原始数据的副本
            # 使用Python函数处理特定字段

            # 执行插入
            dest_cursor.execute(insert_query, processed_user)
            count += 1

            # 分批提交
            if count % batch_size == 0:
                dest_conn.commit()
                print(f"已同步 {count} 条记录")

        dest_conn.commit()  # 提交剩余记录
        print(f"同步完成！总计: {count} 条记录")

    except mysql.connector.Error as err:
        print(f"数据库错误: {err}")
        dest_conn.rollback()
    finally:
        # 关闭连接
        if src_cursor: src_cursor.close()
        if dest_cursor: dest_cursor.close()
        if src_conn: src_conn.close()
        if dest_conn: dest_conn.close()


if __name__ == "__main__":
    sync_user_data()